<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Qt,布局,">










<meta name="description" content="布局管理Qt主要提供了QLayout类及其子类作为布局管理器。">
<meta name="keywords" content="Qt,布局">
<meta property="og:type" content="article">
<meta property="og:title" content="QtCreator学习（2）">
<meta property="og:url" content="http://Anzusen.com/2019/05/02/QtCreator学习（2）/index.html">
<meta property="og:site_name" content="Anzhusen">
<meta property="og:description" content="布局管理Qt主要提供了QLayout类及其子类作为布局管理器。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://anzusen.com/image/QLayout_class_tree.png">
<meta property="og:image" content="http://anzusen.com/image/text_buju.png">
<meta property="og:image" content="http://anzusen.com/image/layout_shuxing.png">
<meta property="og:image" content="http://anzusen.com/image/zhonghe_buju.png">
<meta property="og:image" content="http://anzusen.com/image/QSizePolicy_position.png">
<meta property="og:image" content="http://anzusen.com/QSizePolicy_value.png">
<meta property="og:image" content="http://anzusen.com/image/formLayout_value.png">
<meta property="og:image" content="http://anzusen.com/image/LayoutSize_value.png">
<meta property="og:image" content="http://anzusen.com/image/textEdit_show.png">
<meta property="og:image" content="http://anzusen.com/image/textEdit_hide.png">
<meta property="og:image" content="http://anzusen.com/image/splitter_result.png">
<meta property="og:image" content="http://anzusen.com/image/dingweiqi.png">
<meta property="og:updated_time" content="2020-04-06T13:19:20.382Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="QtCreator学习（2）">
<meta name="twitter:description" content="布局管理Qt主要提供了QLayout类及其子类作为布局管理器。">
<meta name="twitter:image" content="http://anzusen.com/image/QLayout_class_tree.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://Anzusen.com/2019/05/02/QtCreator学习（2）/">





  <title>QtCreator学习（2） | Anzhusen</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/ananzhusen/ananzhusen.github.io" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Anzhusen</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://Anzusen.com/2019/05/02/QtCreator学习（2）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ananzhusen">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/touxiang.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Anzhusen">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">QtCreator学习（2）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-02T10:02:07+08:00">
                2019-05-02
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/QT界面/" itemprop="url" rel="index">
                    <span itemprop="name">QT界面</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/05/02/QtCreator学习（2）/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/05/02/QtCreator学习（2）/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量 <i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  14
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="布局管理"><a href="#布局管理" class="headerlink" title="布局管理"></a>布局管理</h3><p>Qt主要提供了QLayout类及其子类作为布局管理器。<br><a id="more"></a><br><img src="/image/QLayout_class_tree.png" alt="QLayout类关系图"></p>
<h4 id="布局管理系统"><a href="#布局管理系统" class="headerlink" title="布局管理系统"></a>布局管理系统</h4><p>一旦一个部件上设置了布局管理器，那么它会完成以下几种任务:</p>
<ol>
<li>定位子部件;</li>
<li>感知窗口默认大小;➢感知窗口最小大小;</li>
<li>窗口大小变化时进行处理;➢当内容改变时自动更新:</li>
</ol>
<ul>
<li>字体大小、文本或 子部件的其他内容随之改变;</li>
<li>隐藏或显示子部件;</li>
<li>移除一个子 部件。</li>
</ul>
<h5 id="布局管理器"><a href="#布局管理器" class="headerlink" title="布局管理器"></a>布局管理器</h5><p>  QLayout类是布局管理器的基类,是一个抽象基类,継承自QObject 和QLayoutItem类, Qlayoutltem类提供了一个供Qlayout操作的抽象項目。Qlayout 和QLayoutItem都是在设计自己的布局管理器吋オ使用的,一般只需要使用QLayout的几个子类即可,它们分別是QBoxlayout(基本布局管理器)、QGridLayout(柵格布局管理器)、QFormLayout(窗体布局管理器)和QStackedlayout(桟布局管理器)。这里的;QStackedlayout与（1）中述的桟部件QStackedWidget用法相同,不再螯述。<br>  打开Qt Creator ,新建Qt Widgets应用,项目名称为mylayout,基类选择QWidget,类名设为MyWidget。完成后打开mywidget. ui文件,在设计模式中向界面上拖入一个字体选择框Font Combo Box和一个文本编辑器Text Edit部件。然后单击主界面并按下Ctrl+L快捷键,或者单击设计器上部边栏中的 “目” 图标来对主界面进行垂直布局管理。也可以在主界面上右击，在弹出的级联菜单中选择“布局→垂直布局”。这样便设置了顶层布局管理器(因为是对整个窗口设置的布局管理器，所以叫顶层布局管理器),可以看到两个部件已经填满了整个界面。这时运行程序，然后拉伸窗口,两个部件会随着窗口的大小变化而变化,运行结果如图4所示。这就是布局管理器的作用。</p>
<p><img src="/image/text_buju.png" alt="布局管理器随窗口大小变化而变化"></p>
<h6 id="基本布局管理器"><a href="#基本布局管理器" class="headerlink" title="基本布局管理器"></a>基本布局管理器</h6><p>  基本布局管理器QBoxLayout类可以使子部件在水平方向或者垂直方向排成一列,它将所有的空间分成一行盒子，然后将每个部件放人一个盒子中。它有两个子类QHBoxLayout水平布局管理器和QVBoxLayout垂直布局管理器,编程中经常用到。再回到设计模式中看看布局管理器的属性。先单击主界面,查看它的属性栏,最后面的部分是其使用的布局管理器的属性,如下表所列。</p>
<p><img src="/image/layout_shuxing.png" alt="布局管理器的属性"><br>  下面打破已有的布局,使用代码实现水平布局。在界面上右击，然后在弹出的级联菜单中选择“打破布局”,或者单击设计器上方边栏中的打破布局图标。在MyWidget类的构造函数中添加如下代码:</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># <span class="meta-keyword">include</span> <span class="meta-string">&lt; QHBoxLayout&gt;</span></span></span><br><span class="line"></span><br><span class="line">    QHBoxLayout *layout=<span class="keyword">new</span> QHBoxLayout;   <span class="comment">//新建布局管理器</span></span><br><span class="line">    layout-&gt;addWidget(ui-&gt;fontComboBox);   <span class="comment">//向布局管理器中添加部件</span></span><br><span class="line">    layout-&gt;addWidget(ui-&gt;textEdit);       </span><br><span class="line">    layout-&gt;setSpacing(<span class="number">50</span>);                <span class="comment">//设置部件间的间隔</span></span><br><span class="line">    layout-&gt;setContentsMargins(<span class="number">0</span>,<span class="number">0</span>,<span class="number">50</span>,<span class="number">100</span>);<span class="comment">//设置布局管理器到边界的距离</span></span><br><span class="line">                                           <span class="comment">//4个参数顺序是左上右下</span></span><br><span class="line">    setLayout(layout);                     <span class="comment">//将这个布局设置为MyWidget的布局</span></span><br></pre></td></tr></table></figure>
<p><strong>说明：</strong>除了使用addWidget()函数向布局管理器的末尾添加部件外，还可以使用insertWidget()函数向任意位置添加部件。</p>
<h6 id="栅格布局管理器（QGridLayout）"><a href="#栅格布局管理器（QGridLayout）" class="headerlink" title="栅格布局管理器（QGridLayout）"></a>栅格布局管理器（QGridLayout）</h6><p>  栅格布局管理器QGridLayout类使部件在网格中进行布局,它将所有的空间分隔成一些行和列,行和列的交叉处形成了单元格,然后将部件放人一个确定的单元格中。先往界面上拖放一个Push Button, 然后在mywidget. cpp中添加头文件,再注释掉前面添加的关于水平布局管理器的代码,添加的如下代码:<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># <span class="meta-keyword">include</span><span class="meta-string">&lt;QGridLayout&gt;</span></span></span><br><span class="line"></span><br><span class="line">   QGridLayout *layout =<span class="keyword">new</span> QGridLayout;</span><br><span class="line">   <span class="comment">//添加部件从0行0列开始占据一行两列</span></span><br><span class="line">   layout-&gt;addWidget(ui-&gt;fontComboBox,<span class="number">0</span>,<span class="number">0</span>,<span class="number">1</span>,<span class="number">2</span>);</span><br><span class="line">   layout-&gt;addWidget(ui-&gt;pushButton,<span class="number">0</span>,<span class="number">2</span>,<span class="number">1</span>,<span class="number">1</span>);</span><br><span class="line">   layout-&gt;addWidget(ui-&gt;textEdit,<span class="number">1</span>,<span class="number">0</span>,<span class="number">1</span>,<span class="number">3</span>);</span><br><span class="line">   setLayout(layout);</span><br></pre></td></tr></table></figure></p>
<h6 id="窗口布局管理器（QFormLayout）"><a href="#窗口布局管理器（QFormLayout）" class="headerlink" title="窗口布局管理器（QFormLayout）"></a>窗口布局管理器（QFormLayout）</h6><p>  窗体布局管理器QFormLayout类用来管理表单的输人部件以及与它们相关的标签。窗体布局管理器将它的子部件分为两列,左边是一些标签,右边是一些输入部件，比如行编辑器或者数字选择框等。</p>
<p>  先将前面在MyWidget类的构造函数中自己添加的代码全部注释掉,然后进人设计模式,这里使用另外一种方法来使用布局管理器。从部件栏中找到Form Layout,将其拖人到界面上,然后双击或者在它上面右击并在弹出级联菜单中选择“添加窗体布局行”。在弹出的“添加表单布局行”对话框中填入标签文字“姓名(&amp;N):”,这样下面便自动填写了“标签名称”、“字段类型”和“字段名称”等,并且设置了伙伴关系。这里使用了QLineEdit行编辑器,当然也可以选择其他部件。填写的标签文字中的“(&amp;N)”必须是英语半角的括号,表明它的快捷键是Alt+N。设置伙伴关系表示按下Alt+N时，光标自动跳转到标签后面对应的行编辑器中。单击“确定”键.则会在布局管理器中添加一个标签和一个行编辑器。按照这种方法,再添加3行:性别(&amp;S),使用QCo-moBox;年龄(&amp;A),使用QSpinBox;邮箱(&amp;M),使用QLineEdit。完成后运行程序，可以按下快捷键Alt+N,这样光标就可以定位到“姓名”标签后的行编辑器中。</p>
<p>   上面添加表单行是在设计器中完成的,其实也可以在代码中使用addRow()函数来完成。</p>
<h6 id="综合使用布局管理器"><a href="#综合使用布局管理器" class="headerlink" title="综合使用布局管理器"></a>综合使用布局管理器</h6><p>  现在将前面的界面再进行设计:按下Ctrl键的同时选中界面上的字体选择框fontComboBox和按钮pushButton,然后按下Ctrl+H快捷键将它们放人一个水平布局管理器中(其实;也可以从部件栏中拖人一个Horizontal Layout, 然后再将这两个部件放进去，效果是:一样的)。然后再从部件栏中拖入一个Vertical Spacer垂直分隔符,用来在部件间产生间隔,将它放在窗体布局管理器与水平布局管理器之间。最后单击主界面并按下Ctrl+L快捷键,让整个界面处于一个垂直布局管理器中。这时可以在右上角的对象列表中选择分隔符Spacer,然后在属性栏中设置它的高度为100,这时运行程序可以看到,分隔符是不显示的。如图所示：<br><img src="/image/zhonghe_buju.png" alt="综合使用布局管理器"></p>
<h5 id="设置部件大小"><a href="#设置部件大小" class="headerlink" title="设置部件大小"></a>设置部件大小</h5><p>   讲解之前要先了解两个概念:大小提示(sizeHint)和最小大小提示(minimumSize-Hint)。凡是继承自QWidget的类都有这两个属性：</p>
<ul>
<li>sizeHint属性保存了部件的建议大小,对于不同的部件,默认拥有不同的sizeHint;</li>
<li>minimumSizeHint保存了一个建议的最小大小提示。</li>
<li>可以在程序中使用sizeHint()函数来获取sizeHint的值,使用minimumSizeHint( )函数获取minimumSizeHint的值</li>
<li>需要说明的是，如果使用setMinimumSize()函数设置了部件的最小大小，那么最小大小提示将会被忽略。</li>
</ul>
<p>QWidget类的属性：</p>
<ol>
<li>大小策略(sizePolicy)属性，这个属性保存了部件的默认布局行为,在水平和垂直两个方向分别起作用,控制着部件在布局管      下面再来看一下大小策略(sizePolicy)属性,它也是QWidget类的属性。这个属性保存了部件的默认布局行为,在水平和垂直两个方向分别起作用,控制着部件在布局管理器中的大小变化行为。</li>
</ol>
<p>sizePolicy在Qt Creator里的位置及取值：<br><img src="/image/QSizePolicy_position.png" alt="Qtcreator里大小策略的位置"><br><img src="/QSizePolicy_value.png" alt="QSizePolicy大小策略的取值"></p>
<ol start="2">
<li>高度与宽度属性是现在界面的大小;下面的sizePolicy属性可以设置大小策略以及伸缩因子;minimumSize属性用来设置最小值 ;maximumSize属性设置最大值;</li>
<li>sizeIncrement属性和baseSize属性是设置窗口改变大小的，一般不用设置。</li>
</ol>
<p>布局管理器的属性：</p>
<ol>
<li><p>水平布局管理器的layoutStretch属性设置为“2,1”,这样这个水平布局管理器中的两个部件的宽度就是2:1的比例了。如果要在代码中进行设置,则可以在使用布局管理器的addWidget()函数添加部件的同时,在第二个参数中指定伸缩因子。</p>
</li>
<li><p>窗口布局管理器的属性如表所示：</p>
</li>
</ol>
<p><img src="/image/formLayout_value.png" alt="窗口布局属性"></p>
<ol start="3">
<li>LayoutSizeConstraint属它是用来约束窗口大小的，也就是说,这个只对顶级布局管理器有用,因为它只对窗口有用,对其他子部件没有效果。</li>
</ol>
<p><img src="/image/LayoutSize_value.png" alt="约束窗口大小"></p>
<h5 id="可扩展窗口"><a href="#可扩展窗口" class="headerlink" title="可扩展窗口"></a>可扩展窗口</h5><p>  一个窗口可 能有很多选项是扩充的,只有在必要的时候才显示出来,这时就可以使用一个按钮来隐藏或者显示多余的内容,就是所谓的可扩展窗口。要实现可扩展窗口，就要得力于布局管理器的特性,那就是当子部件隐藏时，布局管理器自动缩小，当子部件重新显示时,布局管理器再次放大。下面看一个具体的例子。</p>
<p>  依然在前面的程序中进行更改。首先将界面上的pushButton显示文本更改为“显示可扩展窗口”,并在其属性栏选中checkable选项。然后转到它的toggled( bool)信号的槽,更改如下:</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> MyWidget::on_pushButton_toggled(<span class="keyword">bool</span> checked)<span class="comment">//隐藏窗口按钮</span></span><br><span class="line">&#123;</span><br><span class="line">    ui-&gt;textEdit-&gt;setVisible(checked);<span class="comment">//设置文本编辑器的扩展和隐藏true or false</span></span><br><span class="line">    <span class="keyword">if</span>(checked)ui-&gt;pushButton-&gt;setText(tr(<span class="string">"隐藏可扩展的窗口"</span>));</span><br><span class="line">    <span class="keyword">else</span> ui-&gt;pushButton-&gt;setText(tr(<span class="string">"显示可扩展的窗口"</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>  这里使用按钮的按下与否两种状态来设置文本编辑器是否显示,并且相应地更改按钮的文本。为了让文本编辑器在一开始是隐藏的,还要在MyWidget类的构造函数中添加一行代码:<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ui -&gt;textEdit -&gt;hide();<span class="number">1</span>让文本编辑器隐藏,也可以使用setVisible( <span class="literal">false</span>)函数</span><br></pre></td></tr></table></figure></p>
<p><img src="/image/textEdit_show.png" alt="显示文本编辑器"><br><img src="/image/textEdit_hide.png" alt="隐藏文本显示器"></p>
<h5 id="分裂器（QSplitter）"><a href="#分裂器（QSplitter）" class="headerlink" title="分裂器（QSplitter）"></a>分裂器（QSplitter）</h5><p>  分裂器QSplitter类提供了一个分裂器部件。和QBoxLayout类似，可以完成布局管理器的功能,但是包含在它里面的部件,默认是可以随着分裂器的大小变化而变化的。比如一个按钮放在布局管理器中,它的垂直方向默认是不会被拉伸的,但是放到分裂器中就可以被拉伸。还有一点不同就是,布局管理器继承自QObject类,而分裂器却是继承自QFrame类,QFrame类又继承自QWidget类,也就是说，分裂器拥有QWid-get类的特性,它是可见的,而且可以像QFrame一样设置边框。</p>
<p>  新建Qt Widgets应用,项目名称为mysplitter,基类选择QWidget,类名设为MyWidget。建好项目后打开mywid-get, ui文件,然后往界面上拖人4个Push Button,同时选中这4个按钮,右击并在弹出的级联菜单中选择“布局→使用分裂器水平布局”,将这4个按钮放到一个分裂器中。将分裂器拉大点,并在属性栏中设置其frameShape为Box, frameShadow为Raised,lineWidth为5。运行程序,效果如图所示：<br><img src="/image/splitter_result.png" alt="分裂器运行结果"></p>
<h4 id="设置伙伴（buddy）"><a href="#设置伙伴（buddy）" class="headerlink" title="设置伙伴（buddy）"></a>设置伙伴（buddy）</h4><p>  前面讲述窗体布局管理器时提到了设置一个标签和一个部件的伙伴关系。其实，伙伴( buddy)是在QLabel类中提出的一个概念。因为一个标签经常用作一个交互式部件的说明,就像在讲窗体布局管理器时看到的那样，一个lineEdit部件前面有一个标签说明这个lineEdit的作用。为了方便定位,QLabel提供了一个有用的机制,那就是提供了助记符来定位键盘焦点到对应的部件上,而这个部件就叫这个QLabel的伙伴。其中，助记符就是我们所说的加速键。使用英文标签时,在字符串的一一个字母前面添加“&amp;”符号,就可以指定这个标签的加速键是Alt加上这个字母;对于中文,需要在小括号中指定加速键字母,这个前面已经见过多次了。Qt设计器中也提供了伙伴设计模式,下面看一个例子。</p>
<p>  新建Qt Widgets应用,项目名称为mybuddy,基类选择QWidget,类名设为MyWidget。完成后打开mywidget,ui文件,往界面上拖放4个标签Label, 再在标签后面依次放上PushButton、CheckBox、LineEdit和SpinBox。然后将PushButton前面的标签文本改为“&amp;Button:”, Check-Box前面的标签文本改为“C&amp;heckBox:”,LineEdit前面的标签文本改为“行编辑器(&amp;L):”, SpinBox前面的标签文本改为“数字选择框(&amp;N):”。单击设计器上方边栏中的编辑伙伴图标进入伙伴设计模式,分别将各个标签与它们后面的部件关联起来。然后按下F3键回到正常编辑模式,可以看到所有的&amp;符号都不显示了。<br>  现在运行程序,按下Alt+ B组合键，则可以看到按钮被按下了,而字母下面多了一个横杠,表示这个标签的加速键就是Alt加这个字母。如果要在代码中设置伙伴关系，则只需要使用QLabel的<strong>setBuddy()函数</strong>就可以了。本小节内容可以在帮助索引中通过Qt Designer’s Buddy Editing Mode关键字查看。</p>
<h4 id="设置Tab键顺序"><a href="#设置Tab键顺序" class="headerlink" title="设置Tab键顺序"></a>设置Tab键顺序</h4><p>  对于一个应用程序,有时总希望使用Tab键将焦点从一个部件移动到下一个部件。在设计模式中,设计器提供了Tab键的设置功能。在前面程序的设计模式中,按下，上方边栏的编辑Tab顺序按钮进人编辑Tab键顺序模式,这时已经显示出了各个部件的Tab键顺序,只需要单击这些数字就可以更改顺序。设置好之后,可以运行一下程序测试效果。需要说明，当程序启动时，焦点会在Tab键顺序为1的部件上。这里进行的设置等价于在MyWidget类的构造函数中使用如下代码:</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">setTabOrder(ui -&gt; lineEdit, ui -&gt;spinBox); <span class="comment">//lineEdit 在spinBox前面	</span></span><br><span class="line">   setTabOrder(ui -&gt; spinBox, ui -&gt;pushButton); <span class="comment">// spinBox 在pushButton前面</span></span><br><span class="line">   setTabOrder(ui -&gt; pushButton, ui -&gt;checkBox); <span class="comment">// pushButton在checkBox前面</span></span><br></pre></td></tr></table></figure>
<p>  关于在设计器中设置Tab键顺序,可以在帮助索引中通过Qt Designer’s TabOrder Editing Mode关键字查看。</p>
<h4 id="Qt-Creator中的定位器"><a href="#Qt-Creator中的定位器" class="headerlink" title="Qt Creator中的定位器"></a>Qt Creator中的定位器</h4><p>  定位器,它位于主界面的左下方。使用定位器可以很方便地打开指定文件、定位到文档的指定行、打开一个特定的帮助文档、进行项目中函数的查找等。更多的功能可以在帮助索引中通过Searching With the Locator关键字查看。</p>
<p>   定位器中提供了多个过滤器来实现不同的功能,按下<strong>Ctrl+K</strong>快捷键就会在定位器中显示各个过滤器的前缀及其功能，如图所示。使用方法是<strong>“前缀符号+空格+要定位的内容”</strong>。</p>
<p><img src="/image/dingweiqi.png" alt="定位器"><br>  在Qt Creator中,按下Ctrl+K快捷键打开定位器,这时输人“18”(英文字母1和一个空格,然后是数字8),按下Enter回车键,就会跳转到编辑模式的当前打开文档的第8行。再次按下Ctrl + K快捷键,输入“? qla” ,这时已经查找到了QLabel, 按下回车键,就会跳转到帮助模式中,并打开QLabel类的帮助文档。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你可以对我进行打赏哦</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weichat.jpg" alt="ananzhusen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="ananzhusen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Qt/" rel="tag"># Qt</a>
          
            <a href="/tags/布局/" rel="tag"># 布局</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/28/QtCreator学习（1）/" rel="next" title="QtCreator学习（1）">
                <i class="fa fa-chevron-left"></i> QtCreator学习（1）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/05/04/QtCreator学习（3）/" rel="prev" title="QtCreator学习（3）">
                QtCreator学习（3） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.JPG" alt="ananzhusen">
            
              <p class="site-author-name" itemprop="name">ananzhusen</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/ananzhusen" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5817162963" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gitee.com/anzhusen/" title="gitee" target="_blank">gitee</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#布局管理"><span class="nav-number">1.</span> <span class="nav-text">布局管理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#布局管理系统"><span class="nav-number">1.1.</span> <span class="nav-text">布局管理系统</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#布局管理器"><span class="nav-number">1.1.1.</span> <span class="nav-text">布局管理器</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#基本布局管理器"><span class="nav-number">1.1.1.1.</span> <span class="nav-text">基本布局管理器</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#栅格布局管理器（QGridLayout）"><span class="nav-number">1.1.1.2.</span> <span class="nav-text">栅格布局管理器（QGridLayout）</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#窗口布局管理器（QFormLayout）"><span class="nav-number">1.1.1.3.</span> <span class="nav-text">窗口布局管理器（QFormLayout）</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#综合使用布局管理器"><span class="nav-number">1.1.1.4.</span> <span class="nav-text">综合使用布局管理器</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#设置部件大小"><span class="nav-number">1.1.2.</span> <span class="nav-text">设置部件大小</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#可扩展窗口"><span class="nav-number">1.1.3.</span> <span class="nav-text">可扩展窗口</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#分裂器（QSplitter）"><span class="nav-number">1.1.4.</span> <span class="nav-text">分裂器（QSplitter）</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#设置伙伴（buddy）"><span class="nav-number">1.2.</span> <span class="nav-text">设置伙伴（buddy）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#设置Tab键顺序"><span class="nav-number">1.3.</span> <span class="nav-text">设置Tab键顺序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Qt-Creator中的定位器"><span class="nav-number">1.4.</span> <span class="nav-text">Qt Creator中的定位器</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ananzhusen</span>

  
</div>

<!-- 
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>
 -->



        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站访问总量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'e69lyQSoCtoaLGljT3kXLBEQ-gzGzoHsz',
        appKey: 'pRDcFfyQnO4jQWxElUFupJ2D',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;"></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/src/fireworks.js"></script>
  

</body>
</html>
